// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System;
using System.Data;
using JetBrains.Annotations;
using SnapObjects.Commons;

namespace SnapObjects.Data.PostgreSql
{
    public class PostgreSqlCitextTypeMapping : TypeMapping
    {
        public PostgreSqlCitextTypeMapping(
            [NotNull] string dbTypeName, 
            [NotNull] Type clrType, 
            [CanBeNull] DbType? dbType = null, 
            bool unicode = false, 
            int? size = null) 
            : base(dbTypeName, clrType, dbType, unicode, size)
        {
        }

        public override TypeMapping Clone([NotNull] string dbTypeName, int? size)
        {
            return new PostgreSqlCitextTypeMapping(this.DbTypeName, this.ClrType, this.DbType, this.IsUnicode, this.Size);
        }

        protected override string GenerateNonNullSqlLiteral(object value)
        {
            return $"CITEXT '{this.EscapeSqlLiteral((string)value)}'";
        }

        private string EscapeSqlLiteral([NotNull] string literal)
        {
            return Check.NotNull(literal, nameof(literal)).Replace("'", "''");
        }
    }
}
